package com.winai.launcher.adapter;

import android.app.Dialog;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.TextView;

import com.ks.projectbasictools.base.SimpleView;
import com.ks.projectbasictools.utils.ToastUtil;
import com.winai.launcher.R;
import com.winai.launcher.bean.BleRssiDevice;
import com.winai.launcher.bean.db.BluetoothDeviceBean;
import com.winai.launcher.interfaces.BleConnectCallback;
import com.winai.launcher.manager.AysDeviceManager;
import com.winai.launcher.override.PointView;
import com.winai.launcher.override.ToastKs;
import com.winai.launcher.utils.DialogUtils;
import com.winai.launcher.utils.ScreenUtils;
import com.winai.launcher.utils.Tools;

import java.util.List;

import cn.com.heaton.blelibrary.ble.BleLog;
import cn.com.heaton.blelibrary.ble.callback.BleNotiftCallback;
import cn.com.heaton.blelibrary.ble.callback.BleWriteCallback;
import cn.com.heaton.blelibrary.ble.model.BleDevice;
import cn.com.heaton.blelibrary.ble.utils.ByteUtils;
import cn.com.heaton.blelibrary.ble.utils.ThreadUtils;

public class ScanDeviceAdapter extends RecyclerAdapter<BleRssiDevice> {

    private static final String TAG = "ScanDeviceAdapter";
    private Context mContext;
    private Dialog loadingDialog;
    private ImageView ivLoading;
    private TextView tvTip;
    private Animation loadingAnimation;

    public ScanDeviceAdapter(Context context, List<BleRssiDevice> datas) {
        super(context, R.layout.item_scan, datas);
        mContext = context;
        initDialog();
    }

    @Override
    public void convert(final RecyclerViewHolder hepler, BleRssiDevice rssiDevice) {
        TextView rssi = hepler.getView(R.id.tv_rssi);
        TextView name = hepler.getView(R.id.tv_name);
        TextView address = hepler.getView(R.id.tv_address);
        PointView pointView = hepler.getView(R.id.pointView);

        final BleDevice device = rssiDevice.getDevice();
        rssi.setText(String.format("%ddBm", rssiDevice.getRssi()));
        if (TextUtils.isEmpty(device.getBleName())) {
            name.setText("未知设备");
        } else {
            name.setText(device.getBleName().equals("AYS-013") ? "双头温阳仪" : device.getBleName());
        }
        address.setText(device.getBleAddress());

        BleConnectCallback bcc = new BleConnectCallback() {
            @Override
            public void onConnectionChanged(BleDevice device) {
                if (device.isConnected()) {
                    pointView.setOnline(true);
                } else if (device.isConnectting()) {
                    pointView.setOnline(false);
                } else if (device.isDisconnected()) {
                    pointView.setOnline(false);
                }
            }

            @Override
            public void onConnectException(BleDevice device, int errorCode) {

            }

            @Override
            public void onConnectTimeOut(BleDevice device) {

            }

            @Override
            public void onConnectCancel(BleDevice device) {

            }

            @Override
            public void onServicesDiscovered(BleDevice device, List<BluetoothGattService> services) {
                sendDataForConfigNetwork(device);
            }

            @Override
            public void onReady(BleDevice device) {

            }
        };

        if (device.isConnected()) {
//            ble.disconnect(device);
            pointView.setOnline(true);
            BleLog.e(TAG, "device.isConnected(): " + device.getBleName());
        } else if (device.isConnectting()) {
//            AysDeviceManager.getInstance(mContext).getBle().cancelConnectting(device);
            BleLog.e(TAG, "device.isConnectting(): " + device.getBleName());
        } else if (device.isDisconnected()) {
            BleLog.e(TAG, "device.isDisconnected(): " + device.getBleName());
            AysDeviceManager.getInstance(mContext).startConnect(device, bcc);
        }
    }

    private void sendDataForConfigNetwork(BleDevice bleDevice) {
        showLoading();
        AysDeviceManager.getInstance(mContext).openNotify(bleDevice.getBleAddress(), new BleNotiftCallback<BleDevice>() {
            @Override
            public void onChanged(BleDevice device, BluetoothGattCharacteristic characteristic) {
                Log.e(TAG, String.format("openNotify value: %s%s", "(0x)", ByteUtils.bytes2HexStr(characteristic.getValue())));
                BluetoothDeviceBean bluetoothDeviceBean = new BluetoothDeviceBean();
                switch (bleDevice.getType()) {
                    case 1:
                        bleDevice.setType(2);
                        bluetoothDeviceBean.setAddress(AysDeviceManager.getInstance(mContext).getAddress());
                        bluetoothDeviceBean.setDevice(bleDevice);
                        bluetoothDeviceBean.save();
                        sendWrite(bleDevice, "B0A8010106F0" + bluetoothDeviceBean.getAddress(), "正在设置单播地址");
                        break;
                    case 2:
                        bleDevice.setType(3);
                        sendWrite(bleDevice, "B0A8010208F00000000000", "正在设置IV");
                        break;
                    case 3:
                        bleDevice.setType(4);
                        sendWrite(bleDevice, "B0A801030AF00001" + bluetoothDeviceBean.getNetKey(), "正在设置NetKey");
                        break;
                    case 4:
                        bleDevice.setType(5);
                        sendWrite(bleDevice, "B0A801040CF00001" + bluetoothDeviceBean.getAppKey(), "正在设置AppKey");
                        break;
                    case 5:
                        dismissLoadingDialog();
                        ToastUtil.show(mContext, "配网完成");
                        break;
                }
            }

            @Override
            public void onNotifySuccess(BleDevice device) {
                super.onNotifySuccess(device);
                Log.e(TAG, "onNotifySuccess");
                bleDevice.setType(1);
//                sendWrite(bleDevice, "B0A8010004F0" + AysDeviceManager.getInstance(mContext).getDeviceKey(), "正在设置DeviceKey");
                AysDeviceManager.getInstance(mContext).sendWrite(device.getBleAddress()
                        , "B0A8010004F0" + AysDeviceManager.getInstance(mContext).getDeviceKey()
                        , new BleWriteCallback<BleDevice>() {
                            @Override
                            public void onWriteSuccess(BleDevice device, BluetoothGattCharacteristic characteristic) {
                                ThreadUtils.ui(new Runnable() {
                                    @Override
                                    public void run() {
                                        showLoading();
                                        setLoadingTip("正在设置DeviceKey");
//                                        ToastKs.show(mContext, "正在设置DeviceKey");
                                    }
                                });
                            }

                            @Override
                            public void onWiteFailed(BleDevice device, int failedCode) {
                                super.onWiteFailed(device, failedCode);
                                ThreadUtils.ui(new Runnable() {
                                    @Override
                                    public void run() {
                                        dismissLoadingDialog();
                                        ToastKs.show(mContext, "操作失败:" + failedCode);
                                    }
                                });
                            }
                        });
            }

            @Override
            public void onNotifyCanceled(BleDevice device) {
                super.onNotifyCanceled(device);
                Log.e(TAG, "onNotifyCanceled");
            }
        });
    }


    private void sendWrite(BleDevice bleDevice, String command, String tip) {
        AysDeviceManager.getInstance(mContext).sendWrite(bleDevice.getBleAddress()
                , command
                , new BleWriteCallback<BleDevice>() {
                    @Override
                    public void onWriteSuccess(BleDevice device, BluetoothGattCharacteristic characteristic) {
                        ThreadUtils.ui(new Runnable() {
                            @Override
                            public void run() {
                                setLoadingTip(tip);
                            }
                        });
                    }

                    @Override
                    public void onWiteFailed(BleDevice device, int failedCode) {
                        super.onWiteFailed(device, failedCode);
                        ThreadUtils.ui(new Runnable() {
                            @Override
                            public void run() {
                                dismissLoadingDialog();
                                ToastKs.show(mContext, "操作失败:" + failedCode);
                            }
                        });
                    }
                });
    }

    /**
     * @date 3/16/21
     * @desc 正在检查更新——loading
     */
    private void showLoading() {
        Tools.showDialog(loadingDialog);
        ivLoading.setVisibility(View.VISIBLE);
        ivLoading.startAnimation(loadingAnimation);
    }

    private void initDialog() {
        SimpleView view = new SimpleView(mContext, R.layout.dialog_upgrade_loading);
        initView(view);
        loadingDialog = DialogUtils.dialogCenter(mContext, view, ScreenUtils.dip2px(mContext, 380), true);
        loadingAnimation = AnimationUtils.loadAnimation(mContext, R.anim.anim_loading);
        loadingAnimation.setInterpolator(new LinearInterpolator());
    }

    private void initView(SimpleView view) {
        ivLoading = view.findViewById(R.id.iv_loading);
        tvTip = view.findViewById(R.id.tv_src);
    }

    private void dismissLoadingDialog() {
        Tools.dimssDialog(loadingDialog);
        ivLoading.setVisibility(View.GONE);
        ivLoading.clearAnimation();
    }

    private void setLoadingTip(String tip) {
        tvTip.setText(tip);
    }
}
